package com.example.bookdemo.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.bookdemo.controller.utils.R;
import com.example.bookdemo.domain.Book;
import com.example.bookdemo.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @ Author:郭子木
 * @ Date:2022/6/7
 * @ Time:17:19
 * @ Name:ControllerBook
 * @ Description:
 */
@RestController
@RequestMapping("/books")
public class ControllerBook {
    @Autowired
    private IBookService iBookService;
    private Boolean flag;

    @GetMapping
    public R getAll() throws Exception
    {
        //if (true) throw new Exception();
        return new R(true,iBookService.list());
    }
    @GetMapping("/hello")
    public String Hello()
    {
        return "hello word";
    }

    @PostMapping
    public R save(@RequestBody Book book)
    {
        flag=iBookService.save(book);
        return new R(flag,flag?"执行成功":"执行失败");
    }

    @PutMapping
    public R update(@RequestBody Book book)
    {
        flag=iBookService.updateById(book);
        return new R(flag,flag?"执行成功":"执行失败");
    }

    @DeleteMapping("{id}")
    public R delete(@PathVariable Integer id)
    {
        flag=iBookService.delete(id);
        return new R(flag,flag?"执行成功":"执行失败");
    }

    @GetMapping("{id}")
    public R getById(@PathVariable Integer id)
    {
        return new R(true,iBookService.getById(id));
    }

    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage,@PathVariable int pageSize,Book book)
    {

        IPage<Book> page = iBookService.getPage(currentPage, pageSize,book);
        if (currentPage>page.getPages())
        {
            page = iBookService.getPage((int)page.getPages(), pageSize,book);
        }
        return new R(true,page);
    }
}
